<?php
class NewsAction extends CommonAction {
	function index(){
		$category=D('Category');
		$this->listmap="1 and n.site_id=".$this->siteid;
		$this->listorder="sort,id desc";
		
		if(isset($_GET['category_id'])&&intval($_GET['category_id'])>0){
			$cateids = $category -> getAllIDBypid(intval($_GET['category_id']), $this->siteid);
			$this->listmap.=" and n.category_id in(".implode(',',$cateids).")";
			//dump($cateids);
			$this->category_id=intval($_GET['category_id']);
		}
		
		//搜索标题
		//dump($_GET);
		if($this->_param('keywords')){
			$keywords=$this->_param('keywords');
			$_GET['keywords']=urlencode($this->_param('keywords'));
			$this->listmap.=" and n.title like '%{$keywords}%'";
			$this->keywords=$keywords;
		}
		//栏目筛选
		if(isset($_REQUEST['status']) && intval($_REQUEST['status']) > 0){
			$this->listmap .= " and n.status=1";
			$this->status = 1;
		}
		if(isset($_REQUEST['is_top']) && intval($_REQUEST['is_top']) > 0){
			$this->listmap .= " and n.is_top=1";
			$this->is_top = 1;
		}
		if(isset($_REQUEST['is_hot']) && intval($_REQUEST['is_hot']) > 0){
			$this->listmap .= " and n.is_hot=1";
			$this->is_hot = 1;
		}
		if(isset($_REQUEST['is_rec']) && intval($_REQUEST['is_rec']) > 0){
			$this->listmap .= " and n.is_rec=1";
			$this->is_rec = 1;
		}
		
		
		$pid_list=$category->where(array('pid'=>0,'site_id'=>$this->siteid))->select();
		
		foreach($pid_list as $k=>$v){
			$pid_list[$k]['sub']=$category->getListToArray1($v['id'],$this->siteid);
		}
		$this->assign('pid_list',$pid_list);
        $this->_list();
		if(isMobile()){
			$this->display('indexMobile');
		}else{
			$this->display();
		}
	}
	
	public function selectNews(){
		//增加记录
		if($this->_post('modules_id')){
			$modulesdb = M('Modules');
			$id = $this->_post('id');
			$module = $modulesdb->where(array('id' => $this->_post('modules_id'),'site_id' => $this->siteid))->find();
			//echo $modulesdb->getLastSql();
			if(is_array($module)){
				$modules = unserialize($module['content']);
				$newdata = array();
				
				$isex = false;
				foreach($modules as $k => $v){
					if($v['id'] != $id || $v['module'] == 1){
					    $newdata[] = $v;
					}else{
						$isex = true;
					}
					//是否已经存在记录,是就取消
				}
				//记录不存在增加一条记录
				if(!$isex){
				    $newdata[] = $this->dao->where(array('id' => $id,'site_id' => $this->siteid))->find();
				}
				$ret = $modulesdb->data(array('content' => serialize($newdata)))->where(array('id' => $this->_post('modules_id'),'site_id' => $this->siteid))->save();
				if($ret !== false){
					$data['status'] = 1;
					$data['info'] = '操作成功';
					if(!$isex){
						//新增
						$data['type'] = 1;
					}else{
						$data['type'] = 0;
					}
					exit(json_encode($data));
				}else{
					$this->error($modulesdb->getError());
				}
				
			}else{
				$this->error('当前站点没有这个模块');
			}
			exit();
		}
		if($this->_request('modules_id')){
			$module = M('Modules')->where(array('id' => $this->_get('modules_id'),'site_id' => $this->siteid))->find();
			if(is_array($module)){
				$modules = unserialize($module['content']);
				$selectedid = array();
				foreach($modules as $k => $v){
					if($v['module'] == 0)
					$selectedid[] = $v['id'];
				}
				$this->modules = $modules;
				$this->assign('modules_id', $this->_get('modules_id'));
				$this->assign('selectedid',$selectedid);
			}else{
				$this->error('当前站点没有这个模块');
			}
		}else{
			$this->error('模块ID出错,参数错误');exit;
		}
		$category=D('Category');
		$this->listmap="1 and n.site_id=".$this->siteid;
		$this->listorder="sort,id";
		
		if(isset($_GET['category_id'])&&intval($_GET['category_id'])>0){
			$cateids = $category -> getAllIDBypid(intval($_GET['category_id']), $this->siteid);
			$this->listmap.=" and n.category_id in(".implode(',',$cateids).")";
			//dump($cateids);
			$this->category_id=intval($_GET['category_id']);
		}
		
		//搜索标题
		//dump($_GET);
		if($this->_param('keywords')){
			$keywords=$this->_param('keywords');
			$_GET['keywords']=urlencode($this->_param('keywords'));
			$this->listmap.=" and n.title like '%{$keywords}%'";
			$this->keywords=$keywords;
		}
		//栏目筛选
		if(isset($_REQUEST['status']) && intval($_REQUEST['status']) > 0){
			$this->listmap .= " and n.status=1";
			$this->status = 1;
		}
		if(isset($_REQUEST['is_top']) && intval($_REQUEST['is_top']) > 0){
			$this->listmap .= " and n.is_top=1";
			$this->is_top = 1;
		}
		if(isset($_REQUEST['is_hot']) && intval($_REQUEST['is_hot']) > 0){
			$this->listmap .= " and n.is_hot=1";
			$this->is_hot = 1;
		}
		if(isset($_REQUEST['is_rec']) && intval($_REQUEST['is_rec']) > 0){
			$this->listmap .= " and n.is_rec=1";
			$this->is_rec = 1;
		}
		
		
		$pid_list=$category->where(array('pid'=>0,'site_id'=>$this->siteid))->select();
		
		foreach($pid_list as $k=>$v){
			$pid_list[$k]['sub']=$category->getListToArray1($v['id'],$this->siteid);
		}
		$this->assign('pid_list',$pid_list);
        $this->_list();
		if(isMobile()){
			$this->display('selectNewsMobile');
		}else{
			$this->display();
		}
	
	}
	
	
	function relate(){
		$this->listmap="1 and n.site_id=".$this->siteid;
		$this->listorder="sort,id";
		if(isset($_GET['category_id'])&&intval($_GET['category_id'])>0){
			$this->listmap.=" and n.category_id=".intval($_GET['category_id']);
			$this->category_id=intval($_GET['category_id']);
		}
		
		//搜索标题
		if(isset($_GET['keywords'])&& $_GET['keywords']!=''){
			$keywords=$_GET['keywords'];
			$_GET['keywords']=urlencode($_GET['keywords']);
			$this->listmap.=" and n.title like '%{$keywords}%'";
			$this->keywords=$keywords;
		}
		
		$this->categoryList=M('Category')->where(array('site_id'=>$this->siteid))->select();
        $this->_list();
		$this->display('Public:NewsRelate');
	}
	public function _list(){
		//计算总页数
		$count=$this->dao->alias('n')->join('left join __CATEGORY__ c ON n.category_id= c.id')->Field('n.*,c.title as category_name')->where($this->listmap)->count();
		import ( 'ORG.Util.Page' );
		//实例化分页类
		$p=new Page($count,$this->pagesize);
		$this->list = $this->dao->alias('n')->join('left join __CATEGORY__ c ON n.category_id= c.id')->Field('n.*,c.title as category_name, c.name as cate_name')->where($this->listmap)->order($this->listorder)->limit($p->firstRow.',
'.$p->listRows)->select();
        $this->pages=$p->show();
	}
	
	public function add(){
		$categoryDb = D('Category');
		$this->cate_list = $categoryDb -> getListToArray1(0,$this->siteid);
		//固定栏目及字段扩展
		//用户在栏目列表点击添加文章 
		if($this->_get('category_id')){
			$this->category_id = $this->_get('category_id');
			$this->category = M('Category') -> where(array('id' => $this->category_id)) -> find();
		    $this->extendsField=json_decode($this->category['extends'],true);
		}
		
		parent::add();
	}
	
	public function insert(){
		if(isset($_POST)){
			if($jumpUrl == ''){
			$jumpUrl = (session('jumpUrl')&&session('jumpUrl')!='') ? session('jumpUrl') : U('Admin/' . MODULE_NAME . '/index');
		}
		    $_POST['update_time'] = time();
		    if($this->_post('datetime') == ''){
		        $_POST['datetime'] = time();
			}else{
				$_POST['datetime'] = strtotime($_POST['datetime']);
			}
			if($this->_post('mimg_url')){
				foreach($_POST['mimg_url'] as $k => $v){
					if($v == ''){
						unset($_POST['mimg_url'][$k]);
					}
				}
				$_POST['mimg_url']=implode(',',$_POST['mimg_url']);
				$_POST['site_id']=$this->siteid;
				
			}else{
				$_POST['site_id']=$this->siteid;
				//$_POST['extendsField']=JSON($_POST['extendsField']);
			}
			unset($_POST['modules_id']);
			//相关阅读
			if($this->_post('relateid')){
				$relateid=$this->_post('relateid');
				$relatetitle=$this->_post('relatetitle');
				$relatecate_name=$this->_post('relatecate_name');
				foreach($relateid as $k=>$v){
					$relate[$k]['id']=$relateid[$k];
					$relate[$k]['title']=$relatetitle[$k];
					$relate[$k]['category_name']=$relatecate_name[$k];
				}
				$_POST['relate']=serialize($relate);
			}
			
			$_POST['relateids'] = implode(',', $_POST['relateids']);
			if(!$this->dao->create()){
				$this->error($this->dao->getError());
			}
			$result=$this->dao->add();
			//添加完返回ID号,如果有扩展数据,继续添加
			if(isset($_POST['extendsField'])&&$result>0){
				$flag=true;
				$newsexdb=M('News_extends');
				foreach($_POST['extendsField'] as $k=>$v){
					$d['news_id']=$result;
					$d['name']=$k;
					$d['val']=$v;
					if(!$newsexdb->data($d)->add()){
						$flag=false;
					}
				}
				//如果添加扩展成功提示信息
				if($flag){
					$this->success("成功添加",$jumpUrl);
				}else{
					$this->error($this->dao->getError());
				}
			}elseif($result>0){
				$this->success("成功添加",$jumpUrl);
			}else{
				$this->error($this->dao->getError());
			}
		}
	}
	
	public function edit(){
		if($this->_get('id')){
			$this->cate_list=D('Category')->getListToArray1(0,$this->siteid);
			$id=$this->_get('id');
		    $this->info=$this->dao->where('id='.$id)->find();
			if($this->info['mimg_url']!=''){
			    $this->mimg_url_list=explode(',',$this->info['mimg_url']);
			}
			$this->relateids = explode(',', $this->info['relateids']);
			//dump();
			$relatelist = array();
			foreach($this->relateids as $k => $v){
				$relatelist[] = M('Product') -> where(array('id' => $v, 'site_id' => $this->siteid)) -> find();
			}
			$this->assign('relatelist', $relatelist);
			//固定栏目及字段扩展
			//$this->category = M('Category') -> where(array('id' => $this->info['category_id'])) -> find();
			
			
			
			//扩展信息
			$categorylist = $this->getPageNav($this->info['category_id']);
			foreach($categorylist as $k=>$v){
				if($v['extends']!=''){
					$extendsField = $v['extends'];
				}
			} 
			
			
			
		    $this->extendsField=json_decode($extendsField,true);
			//读取字段扩展数据
			$curexval=M('News_extends')->where(array('news_id'=>$this->_get('id')))->select();
			foreach($curexval as $k=>$v){
				$extendsField_val[$v['name']]=$v['val'];
			}
			$this->assign('extendsField_val',$extendsField_val);
			//相关阅读
			$this->assign('relate',unserialize($this->info['relate']));
			$this->display();
		}else{
			$this->error('参数错误');
		}
	}
	
	private function getPageNav($pid=0){
		$arr=$this->getPageNavArr($pid);
		return array_reverse($arr);
	}
	private function getPageNavArr($pid=0,$arr=array()){
		$re=M('Category')->where(array('id'=>$pid,'site_id'=>$this->siteid))->find();
		if(!is_array($re)){
			return $arr;
		}else{
			$arr[]=$re;
			return $this->getPageNavArr($re['pid'],$arr);
		}
	}
	
	
	public function update(){
	    if($this->_post('id')){
			unset($_POST['modules_id']);
			$_POST['update_time'] == time();
			
			if($this->_post('datetime') == ''){
		        $_POST['datetime'] = time();
			}else{
				$_POST['datetime'] = strtotime($_POST['datetime']);
			}
			if($this->_post('mimg_url')){
				$_POST['mimg_url']=implode(',',$_POST['mimg_url']);
			}else{
				$_POST['mimg_url']='';
			}
			//相关阅读
			if($this->_post('relateid')){
				$relateid=$this->_post('relateid');
				$relatetitle=$this->_post('relatetitle');
				$relatecate_name=$this->_post('relatecate_name');
				foreach($relateid as $k=>$v){
					$relate[$k]['id']=$relateid[$k];
					$relate[$k]['title']=$relatetitle[$k];
					$relate[$k]['category_name']=$relatecate_name[$k];
				}
				$_POST['relate']=serialize($relate);
			}
			$_POST['relateids'] = implode(',', $_POST['relateids']);
			if($this->_post('extendsField')){
				$newexdb=M('News_extends');
			    $oldData=$newexdb->where(array('news_id'=>$this->_post('id')))->select();
				foreach($oldData as $k=>$v){
					$oldname[]=$v['name'];
				}
				//获取老的扩展数据,通过对比,更新或写入新数据
				foreach($_POST['extendsField'] as $k=>$v){
					$u['name']=$k;
					$u['val']=$v;
					$u['news_id']=$this->_post('id');
					if(in_array($k,$oldname)){
						$newexdb->where(array('news_id'=>$this->_post('id'),'name'=>$k))->data($u)->save();
					}else{
						$newexdb->data($u)->add();
					}
					//dump($u);
				}
			} 
			parent::update();
		}
	}
	//删除记录
	public function delete(){
		if($this->_get('id')){
			$map['id']=array('in',$this->_get('id'));
			$result=$this->dao->where($map)->delete();
			$exmap['news_id']=array('in', $this -> _get('id'));
			M('News_extends')->where($exmap)->delete();
			//dump();
			if(false!==$result){
				$this->success('删除成功!',U('index'));
			}else{
			    $this->error('操作失败！');
		    }
		}
	}
	
	
	
	
	//移动到分类
	public function move(){
		if($this->_get('category_id')){
			$category_id=$this->_get('category_id');
			$ids=$this->_get('id');
			$map['id'] = array('in', $ids);
			$data['category_id']=$category_id;
			$re = $this->dao->where($map)->data($data)->save();
			if($re !== false){
			    $this->success('成功移动',U('index'));
			}else{
				$this->error($this->dao->getError());
			}
		}else{
			$this->error('参数错误，没有选择栏目！');
		}
	}
}

?>